<?php

namespace app\admin\controller;

use think\Db;
use think\Session;
use app\api\model\Privatechat;
use app\api\model\Dymanic;
use app\api\model\Task;

class Attestation extends Common {
    private $msg = [1 => '专业认证', 2 => '经验认证', 3 => '患者家属认证', 4 => '机构认证', 5 => '从业者认证', 6 => '擅长话题认证'];
    /**
     * @return mixed
     */
    public function lists() {
        $where = [];

        $types = input('types') ?: 1;
        if ($types) {
            $where['t1.types'] = $types;
        }

        $status = input('status');
        if ($status !== null) {
            $where['t1.status'] = $status;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type == 'data') {
                $where['t1.' . $search_type] = ['like', '%' . $search_name . '%'];
            } else {
                $where['t2.' . $search_type] = $search_name;
            }
        }

        $data = Db::name('user_attestation t1')
            ->field('t1.*, t2.name,t2.phone,t2.sex,t2.age')
            ->join('user t2', 't2.id = t1.user_id', 'left')
            ->where($where)->order('t1.create_time desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item)
            {
                $cates = Db::name('topic')->where(['id'=>['in', $item['category']]])->column('name');
                $item['category_name'] = $cates ? '#'.implode(' #', $cates) : $item['category'];
                $cates = Db::name('dymanic_category')->where(['id'=>['in', $item['cate_id']]])->column('name');
                $item['cate_name'] = $cates ? implode('、', $cates) : $item['cate_id'];
                $item['oss_idx'] = 1;
                $item['face'] = Db::name('auth')->where(['user_id'=>$item['user_id']])->order('id desc')->value('image1');
                return $item;
            });

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);
        $this->assign('status', $status);

        return $this->fetch();
    }

    /**
     * @param $id
     * @return mixed
     */
    public function Watch($id) {
        $name = Db::name('user_attestation')->find($id);
        $this->assign('name', $name);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function Edit() {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {
                $certification = Db::name('user_attestation')->find($id);

                if ($post['status'] == -1) {
                    $status = 3;
                } elseif ($post['status'] == 0) {
                    $status = 1;
                } elseif ($post['status'] == 1) {
                    $status = 2;
                }

                $admin = Session::get('admin', 'mmjtAdmin');
                if ($certification['status'] == 1) {
                    if ($admin['type'] != 1) {
                        return ['err' => '当前账户无权修改，请联系总后台'];
                    }
                }

                $cates = Db::name('topic')->where(['id'=>['in',$certification['category']]])->column('name');
                if ($post['status'] == 1 && !$cates) {
                    return ['err' => '请先分配标签'];
                }


                $result = Db::name('user_attestation')->where('id', $id)->update([
                    'status' => $post['status'],
                    'reason' => input('reason'),
                    'update_time' => datetime(),
                    'audit_time' => datetime(),
                    'audit_admin' => $admin['id']
                ]);

                if (in_array($post['status'], [-1, 1])) {
                    if ($post['status'] == -1) {
                        $content = $this->msg[$certification['types']] . '未通过，请重新提交。原因:' . input('reason');
                    } else {
                        $content = '您的' . $this->msg[$certification['types']] . '已通过。';
                        // 任务
                        $types = [
                            1 => 'doctor_auth',
                            2 => 'case_auth',
                            6 => 'topic_auth',
                        ];
                        Task::finish($types[$certification['types']], $certification['user_id']);
                        // if (in_array($certification['types'], [1,2])) {
                        //     $cates = Db::name('labels')->where(['id'=>['in',$certification['category']]])->column('name');
                        //     $cates = implode('、', $cates);
                        //     if ($certification['types'] == 1) {
                        //         $content = "我擅长的“".$cates."”认证成，可以跟我讨论一下 ".$cates." 康复，医药等医疗问题";
                        //     } else if ($certification['types'] == 2) {
                        //         $content = "“".$cates."”经历认证成功，可以跟我讨论一下 ".$cates." 康复，医药，治疗等经历";
                        //     }
                        //     Dymanic::add([
                        //         'userid'      => $certification['user_id'],
                        //         'content'     => $content,
                        //     ]);
                        // }
                    }

                    Privatechat::notice($certification['user_id'], $content);
                }

                if ($result) {
                    $this->syncToRelang($certification['user_id']);
                }
                
                $data = $result ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            } else {
                $data = ["err" => '参数缺失'];
            }
        } else {
            $name = Db::name('user_attestation')->find($id);
            if ($name) {
                $name['oss_idx'] = $name['user_id'] < 30000000 ? 1 : 0;
            }
            $this->assign('name', $name);
            $data = $this->fetch();
        }
        return $data;
    }

    public function syncToRelang($user_id)
    {
        $user = _channelUser($user_id, 1);
        if (getenv('APP_MALL_DATABASE') == 'database') return $user;
        $remoteDb = Db::connect(getenv('APP_MALL_DATABASE'));
        $del = $remoteDb->name('user_attestation')->where(['user_id'=>$user['id'], 'status'=>1, 'audit_admin'=>0])->delete();
        $auths = Db::name('user_attestation')->where(['user_id'=>$user_id, 'status'=>1, 'types'=>['in', [1,2]]])->select();
        if (empty($auths)) return false;
        $topic_ids = array_unique(array_filter(explode(',', implode(',', array_column($auths, 'category')))));
        $topics = Db::name('topic')->where(['id'=>['in', $topic_ids]])->column('name', 'id');

        $remote_topics = $remoteDb->name('topic')->where(['name'=>['in', array_values($topics)]])->column('id','name');
        foreach ($topics as $key => $value) {
            if (!in_array($value, array_keys($remote_topics))) {
                $id = $remoteDb->name('topic')->insertGetId(['name'=>$value]);
                $remote_topics[$value] = $id;
            }
        }

        $inserts = [];

        foreach ($auths as $key => $value) {
            $category = $value['category']?explode(',', $value['category']):[];
            $newtopic = [];
            foreach ($category as $k => $v) {
                $name = $topics[$v]??'';
                $newtopic[] = $remote_topics[$name]??0;
            }

            $inserts[] = [
                'user_id'=>$user['id'],
                'types'=>$value['types'],
                'category'=>implode(',', array_unique(array_filter($newtopic))),
                'img_a'=>$value['img_a'],
                'img_b'=>$value['img_b'],
                'status'=>1
            ];
        }

        if (sizeof($inserts)) {
            $remoteDb->name('user_attestation')->insertAll($inserts);
        }
    }

    /**
     * @return mixed
     */
    public function Del() {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $res = Db::name('user_attestation')->where(['id' => $id])->find();
                $db  = Db::name('user_attestation')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    public function categoryEdit()
    {
        $id = input("id");
        $checkeddb = db('user_attestation')->where('id', $id)->value('category');
        $t = db('topic')->where(['id'=>['in', $checkeddb]])->select();

        $checkeddb = $checkeddb ? explode(',', $checkeddb) : [];
        $html = '';
        foreach ($t as $k => $v) {
            $html .= '<div class="col-sm-2">';
            $html .= '<div class="radio i-checks">';
            $checked = '';
            foreach ($checkeddb as $cv) {
                if ($cv == $v['id']) {
                    $checked = 'checked';
                    break;
                }
            }
            $html .= '<label><input type="checkbox" ' . $checked . ' value="' . $v['id'] . '" name="data[]">' . $v['name'] . '</label>';
            $html .= '</div></div>';
        }
        $this->assign('labels', $html);
        if (request()->isAjax()) {

            $post = input('post.');
            if (!input('?post.data')) {
                $dataname = false;
            } else {
                $dataname = $post['data'];
            }
            if ($dataname) {
                $cate = implode(',', $dataname);
                $db = db('user_attestation')->where('id', $id)->update(['category' => $cate]);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ['err' => '最少选一个标签'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function shenheAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('user_attestation');
                $admin = Session::get('admin', 'mmjtAdmin');
                foreach ($post as $k => $v) {
                    $certification = Db::name('user_attestation')->find($v);
                    if ($type == 'del') {
                    } else {
                        $update = [
                            'status' => $type,
                            'update_time' => datetime(),
                            'audit_time' => datetime(),
                            'audit_admin' => $admin['id']
                        ];
                        $res = $db->where('id', $v)->update($update);

                        if (in_array($type, [-1, 1])) {
                            if ($type == -1) {
                                $content = $this->msg[$certification['types']] . '未通过，请重新提交。';
                            } else {
                                // 任务
                                $content = '您的' . $this->msg[$certification['types']] . '已通过。';
                                $types = [
                                    1 => 'doctor_auth',
                                    2 => 'case_auth',
                                    6 => 'topic_auth',
                                ];
                                Task::finish($types[$certification['types']], $certification['user_id']);
                            }
                            Privatechat::notice($certification['user_id'], $content);
                        }
                    }
                }
                if ($res) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    public function cateEdit()
    {
        $id = input("id");
        $t = db('dymanic_category')->where('parent_id', 0)->order('des desc,id asc')->select();
        $checkeddb = db('user_attestation')->where('id', $id)->value('cate_id');
        $checkeddb = $checkeddb ? explode(',', $checkeddb) : [];
        $html = '';
        foreach ($t as $k => $v) {
            $html .= '<h5>' . $v['name'] . '<a style="color:skyblue;margin-left:20px;" onClick="add(\''.url('article/addcategory',['tid'=>$v['id'], 'url'=>-1]).'\')">添加下级分类</a></h5>';
            $html .= '<div class="form-group">';
            $html .= '<div class="col-sm-10">';
            $html .= '<div class="radio i-checks">';
            $t2 = db('dymanic_category')->where('parent_id', $v['id'])->order('des desc,id asc')->select();
            if ($t2) {
                foreach ($t2 as $v2) {
                    $checked = '';
                    if ($id) {
                        foreach ($checkeddb as $cv) {
                            if ($cv == $v2['id']) {
                                $checked = 'checked';
                                break;
                            }
                        }
                    }
                    $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v2['id'] . '" name="data[]">' . $v2['name'] . '</label>';
                }
            }
                $html .= '</div></div></div>';
        }
        $this->assign('dymanic_category', $html);
        if (request()->isAjax()) {

            $post = input('post.');;
            if (!input('?post.data')) {
                $dataname = false;
            } else {
                $dataname = $post['data'];
            }
            if ($dataname) {
                $cate = implode(',', $dataname);
                $db = db('user_attestation')->where('id', $id)->update(['cate_id' => $cate]);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ['err' => '最少选一个类别'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

}